package com.lh.sms.utils

import com.aliyuncs.CommonRequest
import com.aliyuncs.CommonResponse
import com.aliyuncs.DefaultAcsClient
import com.aliyuncs.IAcsClient
import com.aliyuncs.exceptions.ClientException
import com.aliyuncs.http.MethodType
import com.aliyuncs.profile.DefaultProfile
import com.lh.sms.conf.SmsProperties
import lombok.extern.slf4j.Slf4j
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.stereotype.Component

/**
 * 短信发送类，使用最新版本阿里云短信服务
 * https://help.aliyun.com/document_detail/101414.html?spm=a2c4g.11186623.2.17.30d623f21K3mKL#doc-api-Dysmsapi-SendSms
 * @author liuhe
 * @date 2020/07/02
 */
@Component
@EnableConfigurationProperties(SmsProperties::class)
class SmsUtils {

    val logger = LoggerFactory.getLogger(this.javaClass);

    @Autowired
    private lateinit var smsProperties: SmsProperties;

    /**
     * @param phone 手机号
     * @param code 验证码，由业务端生成
     * @param signName 签名信息（展示在验证码底部，比如新特汽车、顺丰速运等）
     * @param template 短信模板code，需要在阿里云控制台创建
     *
     */
    fun sendSms(phone: String, code: String, signName: String?, template: String?): CommonResponse? {
        val profile = DefaultProfile.getProfile("cn-hangzhou", smsProperties.accessKeyId, smsProperties.accessKeySecret)
        val client: IAcsClient = DefaultAcsClient(profile)
        val request = CommonRequest()
        request.sysMethod = MethodType.POST
        //产品域名,开发者无需替换
        request.sysDomain = "dysmsapi.aliyuncs.com"
        request.sysVersion = "2017-05-25"
        request.sysAction = "SendSms"
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", template);
        request.putQueryParameter("TemplateParam", "{\"code\":\"$code\"}");

        try {
            val sendSmsResponse = client.getCommonResponse(request)
            logger.info("发送短信状态：" + sendSmsResponse.data);
            return sendSmsResponse;
        } catch (e: ClientException) {
            e.printStackTrace()
        }
        return null;
    }
}